package com.eascs.accessory.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.eascs.accessory.entity.Accessory;
import com.eascs.accessory.entity.O2oAccessoryProvince;
import com.eascs.accessory.form.AccessoryForm;
import com.eascs.accessory.service.AccessoryService;
import com.eascs.admin.o2o.loan.entity.O2oPlatformRegional;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.common.util.StringUtil;
import com.eascs.file.FileService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.vo.ModelResult;

@RestController
@RequestMapping(value = "/accessory")
public class AccessoryRestController extends BaseRestController{

	@Inject
	AccessoryService accessoryService;
	
	@Autowired
	private FileService fileService;

	@RequestMapping(value = "/othfile/{datalist}/{accessoryId}")
	public BaseRestResult<String> othUpload(@RequestParam MultipartFile file, @PathVariable("datalist") String datalist,
			@PathVariable("accessoryId") String accessoryId) {
		fileService.upload(file, datalist, accessoryId);
		insertLog(O2oLogType.FILE_STATUS_N, "上传文件，操作指引文件上传方法");
		return BaseRestResult.buildClosestReloadResult();
	}
	
	/**
	 * 修改操作指引文件上传方法
	 * @Title: updateFileUpload
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @author user
	 * @param file
	 * @param datalist
	 * @param datalistno
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2016年8月16日 下午2:11:43
	 */
	@RequestMapping(value = "/updatefile/{datalist}/{datalistno}")
	public BaseRestResult<String> updateFileUpload(@RequestParam MultipartFile file, @PathVariable("datalist") String datalist,
			@PathVariable("datalistno") String datalistno) {
		System.out.println("datalist:" + datalist + "--datalistno:" +datalistno);
		
		boolean flag = fileService.updateFilePath(file, datalist, datalistno);
		if(flag){
			insertLog(O2oLogType.FILE_STATUS_U, "修改文件，修改操作指引文件上传方法");
			return BaseRestResult.warn("修改文件成功!").andTopRefresh();
		} else{
			return BaseRestResult.warn("修改文件失败!");
		}
	}


	@RequestMapping(value = "/save")
	public BaseRestResult<String> save(AccessoryForm form) {
		ModelResult<String> model = accessoryService.save(form);
		if(model.isSuccess()){
			String result = model.getModel();
			if (result != null) {
				return BaseRestResult.buildRestResult(JSON.toJSONString(result));
			} else {
				return BaseRestResult.warn("新增失败!");
			}
		}else{
			return BaseRestResult.warn("指南code不能重复！");
		}
		
	}
	
	@RequestMapping(value = "/update")
	public BaseRestResult<String> update(AccessoryForm form) {
		ModelResult<String> model = accessoryService.update(form);
		if(model.isSuccess()){
			String result = model.getModel();
			if (result != null) {
				return BaseRestResult.buildRestResult(JSON.toJSONString(result));
			} else {
				return BaseRestResult.warn("修改失败!");
			}
		}else{
			return BaseRestResult.warn("数据库操作失败!");
		}
		
	}

	/**
	 * 
	 * @Title: delete
	 * @Description: 删除指南
	 * @author user
	 * @param accessory
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2016年8月9日 下午2:24:46
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public BaseRestResult<String> delete(Accessory accessory) {
		
		ModelResult<Boolean> model =accessoryService.findFileByAccessroy(accessory.getId());
		if(model.isSuccess()){
			if(model.getModel()){//指南下没有附件，才能删除指南
				ModelResult<Boolean> modelResult = accessoryService.delete(accessory);
				if(modelResult.isSuccess()){
					Boolean result = modelResult.getModel();
					if (result == true) {
						return BaseRestResult.warn("删除成功!");
					} else {
						return BaseRestResult.warn("删除失败!");
					}
				}else{
					return BaseRestResult.warn("数据库操作失败");
				}
			}else{
				return BaseRestResult.buildRestResult("notDone");
			}
		}else{
			return BaseRestResult.warn("数据库操作失败");
		}
	
	
	}
	
	/**
	 * 
	 * @Title: delFile
	 * @Description: 删除指南下的附件
	 * @author user
	 * @param datalistno
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2016年8月9日 下午2:24:46
	 */
	@RequestMapping("/delFile")
	public BaseRestResult<String> delFile(String datalistno) {
		ModelResult<Boolean> modelResult = accessoryService.delFile(datalistno);
		if(modelResult.isSuccess()){
			Boolean result = modelResult.getModel();
			if (result == true) {
				insertLog(O2oLogType.FILE_STATUS_D, "删除文件，删除指南下的附件");
				return BaseRestResult.warn("删除成功!").andTopRefresh();
			} else {
				return BaseRestResult.warn("删除失败!");
			}
		}else{
			return BaseRestResult.warn("数据库操作失败");
		}
		
	}
	/**
	 * 修改操作指引文件弹框页面
	 * @Title: plan
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @author user
	 * @param datalistno 附件库中的主键
	 * @return
	 * @return HtmlRestResult
	 * @throws
	 * @date 2016年8月16日 下午2:10:47
	 */
	@RequestMapping(value = "/accessory/updateFile", method = RequestMethod.GET)
	public HtmlRestResult plan(String datalistno) {
		System.out.println("修改操作指引文件弹框页面" + datalistno);
		ViewContext.put("datalistno", datalistno);
		BaseRestResult.refresh();
		return HtmlRestResult.popHtmlFragment("/accessory/updateFile");
	}
	
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	
	/**
	 * @Description: <p> 插入文件修改日志 </p>
	 * @author CXW
	 * @date 2016年9月26日 下午2:35:13
	 * @version V1.0
	 * @param logType 日志类型,updateStr 修改内容
	 * @return void
	 */
	public void insertLog(String logType,String updateStr){
		try {
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), logType, null, updateStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//跳转附件省份权限界面
	@RequestMapping("/toAddAccProvine")
	public HtmlRestResult toAddAccProvine(String associatedId) {
		//查询省区链表
		List<O2oPlatformRegional> list = accessoryService.getProvinceList();
		//根据附件id查询文档code
		String no = accessoryService.getNoByAssId(associatedId);
		//查询附件已有的省区权限
		List<String> selectList = accessoryService.getSelectProvice(associatedId);
		ViewContext.put("associatedId", associatedId);
		ViewContext.put("no", no);
		ViewContext.put("proList", list);
		ViewContext.put("selectList", selectList);
		return HtmlRestResult.popHtmlFragment("accessory/add_acc_provine");
	}
	
	// 增加附件省份权限
	@RequestMapping(value = "/addAccProvine")
	public BaseRestResult<String> addAccProvine(O2oAccessoryProvince vo) {
		//获取登录人信息
		User user = UserHolder.getUser();
		//获取当前时间
		Calendar cal = Calendar.getInstance();
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
		BaseRestResult<String> results = null;
		if (StringUtil.isNotBlank(vo.getProvinceCode())) {
			//删除附件下的已有权限
			accessoryService.deleteAccProvince(vo.getAssociatedId());
			//对省区权限进行保存
			String[] proArr = vo.getProvinceCode().split(",");
			for (int i = 0; i < proArr.length; i++) {
				String province = accessoryService.getProvinceByCode(proArr[i]);
				O2oAccessoryProvince entity = new O2oAccessoryProvince();
				entity.setAssociatedId(vo.getAssociatedId());
				entity.setDataId(vo.getDataId());
				entity.setProvince(province);
				entity.setProvinceCode(proArr[i]);
				entity.setCreater(user.getCname());
				entity.setCreaterId(user.getNo());
				entity.setCreateDate(date);
				entity.setModifier(user.getCname());
				entity.setModifierId(user.getNo());
				entity.setModifyDate(date);
				accessoryService.saveAccProvince(entity);
			}
			results = BaseRestResult.info("保存成功").andRefresh();
		} else {
			results = BaseRestResult.warn("省份不能为空");
		}
		ViewContext.put("vo", vo);
		return results;
	}
}
